﻿using Carer.Crm.Utility;
using Carer.Data;
using Carer.Data.Cache;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace Carer.Crm.Services
{
    public class UnitService : BaseService
    {
        private static Logger _logger = LogManager.GetLogger("UnitService");
        public IList<Unit> GetAllUnits()
        {
            var allUnits = CacheManager.Get(CacheConst.All_Unit);
            if (allUnits != null)
            {
                var rtn = allUnits as IList<Unit>;
                if (rtn != null && rtn.Count > 0)
                {
                    return rtn;
                }
            }


            string sSql = @"SELECT [Id]
                  ,[Name]
                  ,[Addr]
                  ,[Order]
                  ,[Kind]
                  ,[Remark]
                  ,[Company]
              FROM [dbo].[Unit]
              WHERE 1=1
              ORDER BY [Order]";

            IList<Unit> result = new List<Unit>();
            try
            {
                DataTable dt = SqlHelper.ExecuteDataTable(this.CONN_STR, System.Data.CommandType.Text, sSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        result.Add(new Unit()
                        {
                            Id = row["Id"].ToGetValue(0),
                            Name = row["Name"].ToGetValue(string.Empty),
                            Addr = row["Addr"].ToGetValue(string.Empty),
                            Order = row["Order"].ToGetValue(0),
                            Kind = row["Kind"].ToGetValue(string.Empty),
                            Remark = row["Remark"].ToGetValue(string.Empty),
                            Company = row["Company"].ToGetValue(string.Empty)
                        });
                    }
                }
                CacheManager.Set(CacheConst.All_Unit, result, CacheManager.DAY_1);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "GetAllUnits报错:");
            }

            return result;
        }
    }
}
